import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

class Solution {
    static class TreeNode {
        public int val;
        public TreeNode left;//左孩子的引用
        public TreeNode right;//右孩子的引用

        public TreeNode(int val) {
            this.val = val;
        }
       public List<Integer> postorderTraversal(TreeNode root) {
            List<Integer> list=new ArrayList<>();
            if(root==null){
                return list;
            }
        Stack<TreeNode> stack=new Stack<>();
            TreeNode cur=root;
            while(cur!=null||!stack.isEmpty()){
                while(cur!=null){
                    stack.push(cur);
                    cur=cur.left;
                }
                TreeNode top = stack.peek();
                TreeNode prev=null;
                if(top.right==null||top.right==prev){
                    stack.pop();
                list.add(top.val);
                 prev=top;
                }else{
                    cur=top.right;
                }
            }
            return list;
    }

    /*public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if(root == null) {
            return list;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        TreeNode prev = null;
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode top = stack.peek();
            if(top.right == null || top.right == prev ) {
                stack.pop();
                list.add(top.val);
                prev = top;
            }else {
                cur = top.right;
            }
        }
        return list;
    }*/


    }
}